<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.role_name" placeholder="角色名称" clearable class="filter-item" style="width: 200px;" />
      <el-button class="filter-item search" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="handleRefresh">
        重置
      </el-button>
      <el-button class="filter-item fr" type="primary" icon="el-icon-plus" @click="handleCreateTop">
        新增
      </el-button>
    </div>
    <el-table :data="list" style="width: 100%;margin-bottom: 20px;" row-key="id" border default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="role_name" label="角色名称" />
      <el-table-column prop="identify" label="角色标识" />
      <el-table-column prop="description" label="角色描述" />
      <el-table-column label="创建时间" width="200">
        <template slot-scope="{row}">
          <span>{{ row.create_time|formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="role">
          <!-- <el-button type="primary" icon="el-icon-plus" @click="beforeHandleCreate(role.row)" /> -->
          <el-button type="primary" icon="el-icon-edit" @click="handleUpdate(role.row)" />
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(role.row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <!------------------------- 角色 ------------------------------>
    <el-dialog :title="title" :visible.sync="formVisible" width="30%" @close="handleCancel">
      <el-form :ref="formName" :model="formFieldsData" :rules="rules">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="role_name">
          <el-input v-model="formFieldsData.role_name" placeholder="请输入角色名称" style="width: 92%" autocomplete="off"
            clearable />
        </el-form-item>
        <el-form-item label="角色标识" :label-width="formLabelWidth" prop="identify">
          <el-input v-model="formFieldsData.identify" placeholder="角色标识，路由权限时使用" style="width: 92%" autocomplete="off"
            clearable />
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="formFieldsData.description" style="width: 92%" type="textarea" />
        </el-form-item>
        <el-form-item label="角色权限" :label-width="formLabelWidth">
          <el-tree ref="permissions" :data="permissions" :props="permissionProp" show-checkbox node-key="id"
            :expand-on-click-node="false" />
        </el-form-item>


        <el-input v-model="formFieldsData.parent_id" type="hidden" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    create,
    update,
    deleteRecord,
    getPermissions,
    getRolePermissions,
    getList
  } from '@/api/role'
  import {
    formatDate
  } from '@/utils/formatDate.js'

  export default {
    name: 'roleIndex',

    filters: {
      formatDate(time) {
        time = time * 1000
        let date = new Date(time)

        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        title: '新增',
        formName: 'roles',
        formLabelWidth: '90px',
        formFieldsData: {
          role_name: '',
          identify: '',
          parent_id: 0,
          description: '',
          permissions: [],

        },
        total: 0,
        list: [],
        listQuery: {
          role_name: ''
        },
        permissionProp: {
          label: 'menu_name'
        },
        permissions: [],
        formVisible: false,
        // 验证规则
        rules: {
          role_name: [{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          identify: [{
              required: true,
              message: '请输入角色标识',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 20,
              message: '长度在 3 到 20 个字符',
              trigger: 'blur'
            }
          ]
        },
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        getList(this.listQuery).then(resp => {
          this.list = resp.data
        })
      },
      handleSearch() {
        this.listQuery.page = 1
        this.getList()
      },
      handleRefresh() {
        this.listQuery.menu_name = null
        this.getList()
      },
      handleCreateTop() {
        this.isButton = false
        this.getPermissions()
        this.formFieldsData.parent_id = 0
        this.showType = false
        this.handleCreate()
      },
      getPermissions(roleId) {
        const params = {
          role_id: roleId
        }
        getPermissions(params).then(response => {
          this.permissions = JSON.parse(JSON.stringify(response.data))
        })
      },
      // 弹出层
      handleCreate() {
        this.title = '新增'
        this.id = null
        // 创建前
        if (this.beforeCreate !== undefined) {
          this.beforeCreate()
        }
        this.formVisible = true
      },
      beforeHandleCreate(role) {
        this.getPermissions(role.id)
        this.formFieldsData.parent_id = role.id
        this.handleCreate()
      },
      // 更新
      handleUpdate(record, col, idx) {

        this.title = '更新'
        this.id = record[this.pk !== undefined ? this.pk : 'id']
        // 更新前
        if (this.beforeUpdate !== undefined) {
          this.beforeUpdate(record)
        }
        Object.keys(this.formFieldsData).forEach((k) => {
          this.formFieldsData[k] = record[k]
        })

        this.formVisible = true
      },
      // 更新之前处理
      beforeUpdate(role) {
        this.getPermissions()
        this.setRolePermissions(role.id)
      },
      setRolePermissions(id) {
        getRolePermissions({role_id:id}).then((res) => {
          const permissions = res.data
          //  console.log("ccccc")
          //  console.log(permissions)
          let checked = []
          permissions.map(permission => {
            const node = this.$refs.permissions.getNode(permission.menu_id)
            //console.log(node)
            // if (node.isLeaf) {
              checked.push(permission.menu_id)
            // }
          })
          console.log(checked)
          this.$refs.permissions.setCheckedKeys(checked, true)
        })
      },
      // 关闭
      handleCancel() {
        this.formVisible = false
        // 防止提交关闭的时候 导致数据清空 所以延迟 300ms 清空数据
        setTimeout(this.resetFormFields, 300)
        this.$refs[this.formName].clearValidate()
        if (this.afterCancel !== undefined) {
          this.afterCancel()
        }
      },
      resetFormFields() {
        Object.keys(this.formFieldsData).forEach((k) => {
          switch (typeof this.formFieldsData[k]) {
            case 'object':
              this.formFieldsData[k] = []
              break
            case 'bigint':
              this.formFieldsData[k] = 1
              break
            case 'number':
              if (k === 'parent_id' || k === 'pid') {
                this.formFieldsData[k] = 0
              } else {
                this.formFieldsData[k] = 1
              }
              break
            case 'string':
              this.formFieldsData[k] = ''
              break
            default:
              break

              // eslint-disable-next-line no-unreachable
              if (this.formFieldsDefaultValues !== undefined && this.formFieldsDefaultValues.indexOf(k)) {
                this.formFieldsData[k] = this.formFieldsDefaultValues[k]
              }
          }
        })
      },
      // 删除
      handleDelete(id) {
        if (this.beforeDelete !== undefined) {
          this.beforeDelete()
        }
        deleteRecord({id:id}).then(resp => {
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000,
            onclose: this.getList()
          })

        })
      },
      // 提交
      handleSubmit() {
        if (this.beforeSubmit !== undefined) {
          this.beforeSubmit()
        }

        this.formFieldsData.permissions = this.$refs.permissions.getCheckedKeys();
        this.$refs[this.formName].validate((valid) => {
          if (valid) {
            if (!this.id) {
              create(this.formFieldsData).then(resp => {
                this.formVisible = false
                this.handleRefresh()
                this.resetFormFields()
                this.getList()
              })

            } else {
              this.formFieldsData.id = this.id
              update(this.formFieldsData).then(resp => {
                this.formVisible = false
                this.handleRefresh()
                this.resetFormFields()
                this.getList()
                this.handleUpdateUserInfo()
              })
            }
          } else {
            return false
          }
        })
        this.handleRefresh()
      },
    }
  }
</script>
